package com.weimob.mcloud.wechatwork.customer.facade.impl.sidebar;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.google.common.collect.Lists;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.OrgDepartmentUserExport;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.data.EmployeeBO;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.req.EmployeeDTO;
import com.weimob.mcloud.wechatwork.common.pojo.vo.BasicInfoVO;
import com.weimob.mcloud.wechatwork.common.utils.CollUtils;
import com.weimob.mcloud.wechatwork.core.adapter.enums.bc.InstanceStatusEnum;
import com.weimob.mcloud.wechatwork.core.adapter.enums.channel.ChannelSubType;
import com.weimob.mcloud.wechatwork.core.adapter.enums.channel.WxChannelTypeEnum;
import com.weimob.mcloud.wechatwork.core.adapter.enums.ec.MerchantIssueChannelEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.bos.request.QueryProductInstanceByVidRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.bos.response.ProductInstanceDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.campaign.response.CampaignCategoryConfigBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cdp.request.customer.CDPUserInfoGetDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cdp.response.customer.CDPUserAttributeBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.request.WxChannelInfoFindDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.WxChannelInfoBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cms.request.PmcParameterRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cms.response.PmcAdapterResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.crm.response.CouponsSPIResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.distribution.request.QueryRewardGoodsListRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.distribution.response.QueryRewardGoodsListResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.ec.request.QueryCouponsAdapterRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.ec.response.CouponListAdapterResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.mall.bo.NodeBaseInfoBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.mall.request.*;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.mall.response.*;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.page.PageInfoResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.passport.PhoneAndZoneAndWidResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.pmc.request.PmcRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.pmc.response.PmcResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.shortcode.request.CreateShortCodeRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.shortcode.response.CreateShortCodeResponse;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.spi.order.MallPageInfoResponse;
import com.weimob.mcloud.wechatwork.core.adapter.service.*;
import com.weimob.mcloud.wechatwork.core.adapter.service.cdp.CdpUserAdapterService;
import com.weimob.mcloud.wechatwork.core.base.DomainNameCfgDTO;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.EmployeeIdentity;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Guider;
import com.weimob.mcloud.wechatwork.core.enums.employee.IdentityTypeEnum;
import com.weimob.mcloud.wechatwork.core.enums.privateSphere.TcodeEnum;
import com.weimob.mcloud.wechatwork.core.service.employee.EmployeeService;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.config.CampaignApolloConfig;
import com.weimob.mcloud.wechatwork.customer.convertor.employee.EmployeeConvertor;
import com.weimob.mcloud.wechatwork.customer.convertor.sidebar.SidebarConvertor;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.privateSphere.PrivateSphereServiceProxy;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.usermanagement.EmployeeProxy;
import com.weimob.mcloud.wechatwork.customer.service.user.base.BasicInfo;
import com.weimob.mcloud.wechatwork.customer.service.user.base.PageResponse;
import com.weimob.mcloud.wechatwork.customer.service.user.constant.BaseConstant;
import com.weimob.mcloud.wechatwork.customer.service.user.constant.SidebarConstant;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.*;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BaseErrorCode;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BizException;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.employee.EmployeeIdentityBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.group.CorpChatGroupListBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.mall.NodeSimpleBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.sidebar.*;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.group.CorpChatGroupQueryDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.sidebar.*;
import com.weimob.mcloud.wechatwork.customer.service.user.module.req.mall.StoreSimpleQueryReq;
import com.weimob.mcloud.wechatwork.customer.service.user.service.MallClient;
import com.weimob.mcloud.wechatwork.customer.service.user.service.group.ChatGroupExport;
import com.weimob.mcloud.wechatwork.customer.service.user.utils.SoaResponseUtil;
import com.weimob.mcloud.wechatwork.customer.third.PrivateSphereThird;
import com.weimob.mcloud.wechatwork.customer.third.UrlConverProxy;
import com.weimob.mcloud.wechatwork.customer.third.customer.CustomerThird;
import com.weimob.mcloud.wechatwork.customer.third.passport.PassPortAccountFetchProxy;
import com.weimob.mcloud.wechatwork.customer.third.pmc.PmcProxy;
import com.weimob.mcloud.wechatwork.customer.utils.UrlQueryUtil;
import com.weimob.shorturl.model.UrlErrorVo;
import com.weimob.shorturl.model.response.GetShortCodeResponse;
import com.weimob.shorturl.service.ShortParamService;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author yu liu  2021/11/23 17:31
 * Description
 * Version 1.0.0
 **/
@Slf4j
@Service
public class SidebarFacade {
    @Reference
    private PrivateSphereService privateSphereService;
    @Reference
    private BosAdapterService bosAdapterService;
    @Reference
    private EmployeeService employeeService;
    @Reference
    private OneCrmAdapterService oneCrmAdapterService;
    @Reference
    private ShortCodeAdapterService shortCodeAdapterService;
    @Reference
    private EcAdapterService ecAdapterService;
    @Reference
    private MallAdapterService mallAdapterService;
    @Reference
    private CRMAdapterService crmAdapterService;
    @Reference
    private CMSAdapterService cmsAdapterService;
    @Reference
    private OrgDepartmentUserExport orgDepartmentUserExport;
    @Reference
    private CdpUserAdapterService cdpUserAdapterService;
    @Autowired
    private ChannelAdapterService channelAdapterService;
    @Reference
    private AcAdapterService acAdapterService;
    @Reference
    private ChatGroupExport chatGroupExport;
    @Reference
    private MallClient mallClient;
    @Reference
    private ShortParamService shortParamService;
    @Resource
    private DistributionAdapterService distributionAdapterService;

    @Autowired
    private CustomerThird customerThird;
    @Autowired
    private PassPortAccountFetchProxy passPortAccountFetchProxy;
    @Autowired
    private PmcProxy pmcProxy;
    @Autowired
    private UrlConverProxy urlConverProxy;
    @Autowired
    private PrivateSphereThird privateSphereThird;
    @Autowired
    private PrivateSphereServiceProxy privateSphereServiceProxy;

    @Autowired
    private CampaignApolloConfig campaignApolloConfig;

    @Value("${mall.productid}")
    private Long mallProductId;
    @Value("${crm.productid}")
    private Long crmProductId;
    @Value("${guide.productid}")
    private Long guideProductId;
    @ApolloJsonValue("${domain.name.by.tcode}")
    private DomainNameCfgDTO domainNameCfgDTO;

    @Autowired
    private EmployeeProxy employeeProxy;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;

    private PrivateSphere getPrivateSphereByBasicInfo(BasicInfo basicInfo) {
        PrivateSphere privateSphere = new PrivateSphere();
        if (basicInfo != null) {
            BeanUtils.copyProperties(basicInfo, privateSphere);
            if (null == privateSphere.getProductId()) {
                privateSphere.setProductId(aewcProductId);
            }
            privateSphere = SoaUtil.unpack(privateSphereService.fetch(privateSphere));
        }
        return privateSphere;
    }

    public SidebarAuthBO getSidebarAuth(SidebarCommonDTO sidebarCommonDTO) {
        PrivateSphere privateSphere = this.getPrivateSphereByBasicInfo(sidebarCommonDTO.getBasicInfo());

        Integer authType = SidebarAuthEnum.HAVE_AUTH.getCode();


        // 查根节点开通的产品 目前前端做这个校验
//        QueryProductInstanceOfRootVidRequest queryProductInstanceOfRootVidRequest = new QueryProductInstanceOfRootVidRequest();
//        queryProductInstanceOfRootVidRequest.setBosId(privateSphere.getBosId());
//        queryProductInstanceOfRootVidRequest.setProductIdList(Lists.newArrayList(BaseConstant.WECHATWORK_PRODUCT_ID,
//                mallProductId, crmProductId));
//        List<ProductInstanceDTO> productInstanceDTOS = SoaUtil.unpack(bosAdapterService.queryProductInstanceOfRootVid(queryProductInstanceOfRootVidRequest));
//        Boolean wechatworkProduct = false;
//        Boolean mallProduct = false;
//        Boolean CRMProduct = false;
//        if (CollectionUtils.isNotEmpty(productInstanceDTOS)) {
//            for (ProductInstanceDTO productInstanceDTO : productInstanceDTOS) {
//                // 企微高级版产品
//                if (BaseConstant.WECHATWORK_PRODUCT_ID == productInstanceDTO.getProductId()
//                        && BaseConstant.WECHATWORK_PE_PRODUCT_VERSION_ID == productInstanceDTO.getProductVersionId()
//                        && StringUtils.equals(InstanceStatusEnum.IN_USE.getCode(), productInstanceDTO.getStatusCode())) {
//                    wechatworkProduct = true;
//                }
//                // 商城产品
//                if (mallProductId == productInstanceDTO.getProductId()
//                        && StringUtils.equals(InstanceStatusEnum.IN_USE.getCode(), productInstanceDTO.getStatusCode())) {
//                    mallProduct = true;
//                }
//                // CRM产品
//                if (146L == productInstanceDTO.getProductId()
//                        && StringUtils.equals(InstanceStatusEnum.IN_USE.getCode(), productInstanceDTO.getStatusCode())) {
//                    CRMProduct = true;
//                }
//            }
//        }
//        // 校验权限
//        if (SidebarConstant.SIDEBAR_PAGETYPE_AUTH_COUPON == sidebarCommonDTO.getSidebarType()) {
//            if (!(wechatworkProduct && CRMProduct)) {
//                authType = SidebarAuthEnum.NONE_CRM.getCode();
//            }
//        } else {
//            if (!(wechatworkProduct && mallProduct)) {
//                authType = SidebarAuthEnum.NONE_MALL.getCode();
//            }
//        }

        //4、获取员工wid
        Employee employee = employeeProxy.fetchEmployeeById(privateSphere, sidebarCommonDTO.getUserId(), null);

        if (employee == null || StringUtils.isEmpty(employee.getMobile())) {
            authType = SidebarAuthEnum.NONE_WID.getCode();
        } else {
            Long wid =
                    SoaUtil.unpack(acAdapterService.getWidByPhone(employee.getMobile()));
            if (wid == null || wid == 0L) {
                authType = SidebarAuthEnum.NONE_WID.getCode();
            }
        }

        SidebarAuthBO sidebarAuthBO = new SidebarAuthBO();
        sidebarAuthBO.setAuthType(authType);
        return sidebarAuthBO;
    }

    /**
     * 侧边栏员工访问权限 目前这里主要是员工身份信息
     *
     * @author jun.liu05
     * @since 1.0
     */
    public SidebarEmployeeAuthBO getSidebarEmployeeAuth(SidebarCommonDTO sidebarCommonDTO) {
        PrivateSphere privateSphere = this.getPrivateSphereByBasicInfo(sidebarCommonDTO.getBasicInfo());

        //4、获取员工wid
        Employee employee = employeeProxy.fetchEmployeeById(privateSphere, sidebarCommonDTO.getUserId(), null);

        SidebarEmployeeAuthBO sidebarEmployeeAuthBO = new SidebarEmployeeAuthBO();
        sidebarEmployeeAuthBO.setEmployeeId(employee.getId());
        List<EmployeeIdentityBO> list = CollUtils.map(employee.getEmployeeIdentityList(), EmployeeConvertor::getEmployeeIdentityBO, Boolean.FALSE);
        sidebarEmployeeAuthBO.setEmployeeIdentityBOList(list);

        return sidebarEmployeeAuthBO;
    }

    /**
     * 通过侧边栏类型查询需要查的vidTypes
     *
     * @param sideBarType 参考SidebarConstant
     * @return list
     */
    private List<Integer> getVidTypesBySidebarType(Integer sideBarType) {
        if (SidebarConstant.SIDEBAR_PROMOTIONAL_ACTIVITIES.equals(sideBarType)) {
            return Lists.newArrayList(VidTypeEnum.VID_SHOP.getCode(), VidTypeEnum.VID_BRAND.getCode(), VidTypeEnum.VID_AREA.getCode());
        } else {
            return Lists.newArrayList(VidTypeEnum.VID_SHOP.getCode(), VidTypeEnum.VID_BRAND.getCode());
        }
    }

    /**
     * 员工身份是导购按照导购归属门店展示（不可切换节点）、员工身份非导购则
     * ①单聊按客户归属门店展示vid。
     * ②群聊按群归属门店展示vid；
     * ③无归属门店则按品牌节点展示（节点可切换）；
     *
     * @param sidebarStoreDTO
     * @return
     */
    public SidebarStoreBO getDefaultStore(SidebarStoreDTO sidebarStoreDTO) {
        //入参校验
        if (StringUtils.isEmpty(sidebarStoreDTO.getUserId())) {
            throw new BizException(BaseErrorCode.PARMA_EXCPETION.getCode(), BaseErrorCode.PARMA_EXCPETION.getMsg());
        }
        //获取私域
        PrivateSphere privateSphere = this.getPrivateSphereByBasicInfo(sidebarStoreDTO.getBasicInfo());

        //根据vid类型 查询vid数据
        StoreSimpleQueryReq storeSimpleQueryReq = new StoreSimpleQueryReq();
        storeSimpleQueryReq.setPageNum(1);
        storeSimpleQueryReq.setPageSize(999);
        storeSimpleQueryReq.setBasicInfo(sidebarStoreDTO.getBasicInfo());
        storeSimpleQueryReq.setVidTypes(getVidTypesBySidebarType(sidebarStoreDTO.getSidebarType()));

        PageResponse<NodeSimpleBO> storeList = SoaUtil.unpack(mallClient.queryStorePage(storeSimpleQueryReq));
        List<NodeSimpleBO> nodeList = storeList.getResults();

        //将品牌的排在最前面，默认品牌（nodeList按vidType升序排序）
        if (CollectionUtils.isNotEmpty(nodeList)) {
            nodeList.sort((n1, n2) -> {
                Integer n1Type = n1.getVidTypes().get(0);
                Integer n2Type = n2.getVidTypes().get(0);
                return n1Type.compareTo(n2Type);
            });
        }

        SidebarStoreBO sidebarStoreBO = new SidebarStoreBO();
        // 1. 除了订单默认第一个门店
        if (!SidebarConstant.SIDEBAR_PAGETYPE_AUTH_ORDER.equals(sidebarStoreDTO.getSidebarType())) {
            if (CollectionUtils.isNotEmpty(nodeList)) {
                sidebarStoreBO.setDefaultVid(nodeList.get(0).getVid());
                sidebarStoreBO.setDefaultVidName(nodeList.get(0).getVidName());
                sidebarStoreBO.setDefaultVidTypes(nodeList.get(0).getVidTypes());
            }
        }


        // 2. 判断员工是否导购归属门店，是否开通产品
        Employee employee = employeeProxy.fetchEmployeeById(privateSphere, sidebarStoreDTO.getUserId(), null, true);


        Long productId = null;
        if (SidebarConstant.SIDEBAR_PAGETYPE_AUTH_COUPON.equals(sidebarStoreDTO.getSidebarType())) {
            productId = crmProductId;
        }
        if (SidebarConstant.SIDEBAR_PAGETYPE_AUTH_GOODS.equals(sidebarStoreDTO.getSidebarType())
                || SidebarConstant.SIDEBAR_PAGETYPE_AUTH_ORDER.equals(sidebarStoreDTO.getSidebarType())
                || SidebarConstant.SIDEBAR_PROMOTIONAL_ACTIVITIES.equals(sidebarStoreDTO.getSidebarType())
                || SidebarConstant.SIDEBAR_PAGETYPE_AUTH_GET_CUSTOMERS_ACTIVITY.equals(sidebarStoreDTO.getSidebarType())) {
            productId = mallProductId;
        }

        Boolean isGuide = employee != null && CollectionUtils.isNotEmpty(employee.getGuiderList());
        if (Boolean.TRUE.equals(isGuide)) {
            ProductInstanceDTO productInstanceDTO = this.getProductByVid(employee.getGuiderList().get(0).getStoreId(), productId);
            if (productInstanceDTO != null) {
                sidebarStoreBO.setDefaultVid(employee.getGuiderList().get(0).getStoreId());
                sidebarStoreBO.setDefaultVidName(employee.getGuiderList().get(0).getStoreName());
                sidebarStoreBO.setGuideWid(employee.getGuiderList().get(0).getWid());
                sidebarStoreBO.setGuideVid(employee.getGuiderList().get(0).getStoreId());
                sidebarStoreBO.setBelongGuiderStoreFlag(true);
                //查询vidTypes
                List<Integer> vidTypes = getVidTypes(sidebarStoreBO.getDefaultVid(), privateSphere.getBosId());
                //赋值
                sidebarStoreBO.setDefaultVidTypes(vidTypes);
                return sidebarStoreBO;
            }
        }

        if (StringUtils.isEmpty(sidebarStoreDTO.getExternalUserId()) && StringUtils.isEmpty(sidebarStoreDTO.getChatId())) {
            return sidebarStoreBO;
        }

        // 3. 判断单聊群聊归属门店，是否开通产品
        Long belongStoreId = null;
        String belongStoreName = null;
        if (StringUtils.isNotEmpty(sidebarStoreDTO.getExternalUserId())) {
            //3、获取用户wid
            Long wid = customerThird.getSuperWid(privateSphere.getBosId(), sidebarStoreDTO.getExternalUserId(), privateSphere.getCorpId());

            if (wid != null) {
                CDPUserInfoGetDTO cdpUserInfoGetDTO = new CDPUserInfoGetDTO();
                cdpUserInfoGetDTO.setBosId(privateSphere.getBosId());
                cdpUserInfoGetDTO.setCorpId(privateSphere.getCorpId());
                cdpUserInfoGetDTO.setWid(wid);
                CDPUserAttributeBO cdpUserAttributeBO = SoaUtil.unpack(cdpUserAdapterService.getCDPBaseUserInfo(cdpUserInfoGetDTO));
                if (cdpUserAttributeBO != null && cdpUserAttributeBO.getStoreId() != null && cdpUserAttributeBO.getStoreId() != 0L) {
                    belongStoreId = cdpUserAttributeBO.getStoreId();
                    if (CollectionUtils.isNotEmpty(nodeList)) {
                        belongStoreName = nodeList.stream().filter(item -> item.getVid().equals(cdpUserAttributeBO.getStoreId())).findFirst().orElse(new NodeSimpleBO()).getVidName();
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(sidebarStoreDTO.getChatId())) {
            // 群聊归属门店
            CorpChatGroupQueryDTO corpChatGroupQueryDTO = new CorpChatGroupQueryDTO();
            corpChatGroupQueryDTO.setCorpId(privateSphere.getCorpId());
            corpChatGroupQueryDTO.setChatId(sidebarStoreDTO.getChatId());
            corpChatGroupQueryDTO.setBasicInfo(sidebarStoreDTO.getBasicInfo());
            corpChatGroupQueryDTO.setPageNum(1);
            corpChatGroupQueryDTO.setPageSize(10);
            //查询客户群列表数据
            PageResponse<CorpChatGroupListBO> groupListBOPagination = SoaResponseUtil.unpack(chatGroupExport.listGroupJoinStore(corpChatGroupQueryDTO));
            if (CollectionUtils.isNotEmpty(groupListBOPagination.getResults())) {
                String retailStoreId = groupListBOPagination.getResults().get(0).getRetailStoreId();
                if (StringUtils.isNotEmpty(retailStoreId)) {
                    belongStoreId = Long.parseLong(retailStoreId);
                    belongStoreName = groupListBOPagination.getResults().get(0).getRetailStoreName();
                }
            }
        }
        // 归属门店是否开通对应产品
        ProductInstanceDTO productInstanceDTO = null;
        if (belongStoreId != null && belongStoreId > 0L) {
            productInstanceDTO = this.getProductByVid(belongStoreId, productId);
            if (productInstanceDTO != null) {
                sidebarStoreBO.setDefaultVid(belongStoreId);
                sidebarStoreBO.setDefaultVidName(belongStoreName);
            }
        }
        //查询vidTypes
        List<Integer> vidTypes = getVidTypes(sidebarStoreBO.getDefaultVid(), privateSphere.getBosId());
        //赋值
        sidebarStoreBO.setDefaultVidTypes(vidTypes);

        return sidebarStoreBO;
    }

    /**
     * 通过vid获取vidTypes
     *
     * @param vid   vid
     * @param bosId bosId
     * @return list
     */
    private List<Integer> getVidTypes(Long vid, Long bosId) {
        if (Objects.isNull(vid) || Objects.isNull(bosId)) {
            log.warn("getVidTypes vid or bosId入参为空,vid:{},bosId:{}", vid, bosId);
            return Collections.emptyList();
        }

        StoreQueryReq storeQueryReq = new StoreQueryReq();
        storeQueryReq.setBosId(bosId);
        storeQueryReq.setVids(Lists.newArrayList(vid));
        storeQueryReq.setPageSize(1);
        storeQueryReq.setPageNum(1);
        SoaResponse<PageInfoResponse<StoreResponse>, ?> pageInfoResponseSoaResponse = mallAdapterService.queryStorePage(storeQueryReq);
        PageInfoResponse<StoreResponse> storeResponse = SoaUtil.unpack(pageInfoResponseSoaResponse);
        if (CollectionUtils.isEmpty(storeResponse.getDataList())) {
            log.warn("getDefaultStore.queryStorePage,未查询到默认门店,vid:{}", vid);
            return Collections.emptyList();
        }

        List<StoreResponse> dataList = storeResponse.getDataList();
        NodeBaseInfoBO nodeBaseInfoBO = dataList.get(0).getNodeBaseInfoBO();
        if (Objects.isNull(nodeBaseInfoBO)) {
            return Collections.emptyList();
        }

        return nodeBaseInfoBO.getVidTypes();
    }

    // 获取节点的产品等信息
    public ProductInstanceDTO getProductByVid(Long vid, Long productId) {
        QueryProductInstanceByVidRequest queryProductInstanceByVidRequest = new QueryProductInstanceByVidRequest();
        queryProductInstanceByVidRequest.setVid(vid);
        queryProductInstanceByVidRequest.setProductIdList(Lists.newArrayList(productId));

        List<ProductInstanceDTO> productInstanceDTOList = SoaUtil.unpack(bosAdapterService.queryProductInstanceByVid(queryProductInstanceByVidRequest));
        if (CollectionUtils.isNotEmpty(productInstanceDTOList)
                && StringUtils.equals(InstanceStatusEnum.IN_USE.getCode(), productInstanceDTOList.get(0).getStatusCode())) {
            return productInstanceDTOList.get(0);
        }
        return null;
    }


    public List<GoodsClassifyBO> getGoodsClassifyList(GoodsClassifyDto goodsClassifyDto) {
        if (goodsClassifyDto.getCurrentVid() == null || goodsClassifyDto.getCurrentVid() == 0L) {
            throw new BizException(BaseErrorCode.CURRENTVID_IS_EMPTY.getCode(), BaseErrorCode.CURRENTVID_IS_EMPTY.getMsg());
        }
        ProductInstanceDTO productByVid = this.getProductByVid(goodsClassifyDto.getCurrentVid(), mallProductId);
        if (productByVid == null) {
            throw new BizException("无法获取门店信息");
        }

        ClassifyQueryAdapterRequest classifyQueryAdapterRequest = new ClassifyQueryAdapterRequest();
        classifyQueryAdapterRequest.setBosId(productByVid.getBosId());
        classifyQueryAdapterRequest.setMerchantId(productByVid.getMerchantId());
        classifyQueryAdapterRequest.setProductId(productByVid.getProductId());
        classifyQueryAdapterRequest.setProductInstanceId(productByVid.getProductInstanceId());
        classifyQueryAdapterRequest.setVid(goodsClassifyDto.getCurrentVid());
        classifyQueryAdapterRequest.setParentId(goodsClassifyDto.getParentId());
        classifyQueryAdapterRequest.setIsSystemClassifyShow(true);
        classifyQueryAdapterRequest.setHiddenSysClassifyShow(true);
        classifyQueryAdapterRequest.setIsQueryRelationCategory(true);
        classifyQueryAdapterRequest.setIsQueryRelationGoodsCount(true);
        classifyQueryAdapterRequest.setPageNum(1);
        classifyQueryAdapterRequest.setPageSize(200);

        ClassifyListAdapterResponse unpack = SoaUtil.unpack(mallAdapterService.getGoodsClassifyList(classifyQueryAdapterRequest));

        List<GoodsClassifyBO> goodsClassifyBOList = new ArrayList<>();
        if (unpack == null) {
            return goodsClassifyBOList;
        }

        List<GoodsClassifyResponse> goodsClassifyList;
        if (goodsClassifyDto.getQuerySystemClassify()) {
            // 系统分组
            goodsClassifyList = unpack.getSystemClassifyList();
        } else {
            // 自定义分组
            goodsClassifyList = unpack.getGoodsClassifyList();
        }
        if (CollectionUtils.isNotEmpty(goodsClassifyList)) {
            for (GoodsClassifyResponse goodsClassify : goodsClassifyList) {
                GoodsClassifyBO goodsClassifyBO = new GoodsClassifyBO();
                BeanUtils.copyProperties(goodsClassify, goodsClassifyBO);
                goodsClassifyBOList.add(goodsClassifyBO);
            }
        }

        return goodsClassifyBOList;
    }

    public PageResponse<SidebarGoodsBO> getGoodsList(SidebarGoodsDTO sidebarGoodsDTO) {
        if (sidebarGoodsDTO.getCurrentVid() == null || sidebarGoodsDTO.getCurrentVid() == 0L) {
            throw new BizException(BaseErrorCode.CURRENTVID_IS_EMPTY.getCode(), BaseErrorCode.CURRENTVID_IS_EMPTY.getMsg());
        }
        ProductInstanceDTO productByVid = this.getProductByVid(sidebarGoodsDTO.getCurrentVid(), mallProductId);
        if (productByVid == null) {
            throw new BizException("无法获取门店信息");
        }
        // 获取appid
        WxChannelInfoBO wxChannelInfoBO = this.getWxChannelInfo(productByVid.getBosId(), productByVid.getProductInstanceId());

        QueryGoodsListAdapterRequest queryGoodsListAdapterRequest = new QueryGoodsListAdapterRequest();
        queryGoodsListAdapterRequest.setBosId(productByVid.getBosId());
        queryGoodsListAdapterRequest.setMerchantId(productByVid.getMerchantId());
        queryGoodsListAdapterRequest.setProductId(productByVid.getProductId());
        queryGoodsListAdapterRequest.setProductInstanceId(productByVid.getProductInstanceId());
        queryGoodsListAdapterRequest.setVid(sidebarGoodsDTO.getCurrentVid());
        if (wxChannelInfoBO != null) {
            queryGoodsListAdapterRequest.setCid(wxChannelInfoBO.getcAppId());
        }

        queryGoodsListAdapterRequest.setSearch(sidebarGoodsDTO.getSearch());
        queryGoodsListAdapterRequest.setSearchType(sidebarGoodsDTO.getSearchType());

        queryGoodsListAdapterRequest.setSearchOptionType(1);
        queryGoodsListAdapterRequest.setClassifyId(sidebarGoodsDTO.getClassifyId());
        queryGoodsListAdapterRequest.setSort(sidebarGoodsDTO.getSort());
        queryGoodsListAdapterRequest.setSortType(sidebarGoodsDTO.getSortType());
        queryGoodsListAdapterRequest.setSource(sidebarGoodsDTO.getSource());
        queryGoodsListAdapterRequest.setIsCanSell(SidebarConstant.YES);
        queryGoodsListAdapterRequest.setGoodsStatus(SidebarConstant.PUT_AWAY_STATUS_ON);
        queryGoodsListAdapterRequest.setSaleChannelType(Lists.newArrayList(SidebarConstant.SALE_CHANNEL_ONLINE, SidebarConstant.SALE_CHANNEL_ONANDOFF_LINE));
        queryGoodsListAdapterRequest.setPageNum(sidebarGoodsDTO.getPageNum());
        queryGoodsListAdapterRequest.setPageSize(sidebarGoodsDTO.getPageSize());

        PageInfoResponse<QueryGoodsListAdapterResponse> unpack = new PageInfoResponse<>();
        try {
            log.info("查询商品列表接口: bosId:{}", queryGoodsListAdapterRequest.getBosId());
            unpack = SoaUtil.unpack(mallAdapterService.getGoodsList(queryGoodsListAdapterRequest));
        } catch (Exception e) {
            log.error("获取商品列表的接口发生异常，请求参数：{}，错误内容：", queryGoodsListAdapterRequest, e);
        }

        if (null == unpack || CollectionUtils.isEmpty(unpack.getDataList())) {
            return new PageResponse<>(Lists.newArrayList(), sidebarGoodsDTO.getPageNum(),
                    sidebarGoodsDTO.getPageSize(), 0L);
        }

        List<SidebarGoodsBO> sidebarGoodsBOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(unpack.getDataList())) {
            for (QueryGoodsListAdapterResponse item : unpack.getDataList()) {
                SidebarGoodsBO sidebarGoodsBO = new SidebarGoodsBO();
                BeanUtils.copyProperties(item, sidebarGoodsBO);
                sidebarGoodsBO.setId(item.getGoodsId());
                if (item.getOnlineTime() != null) {
                    sidebarGoodsBO.setPutAwayDate(item.getOnlineTime());
                }
                sidebarGoodsBO.setSalePrice(item.getMinSalePrice());
                if (item.getGoodsStockNum() != null) {
                    sidebarGoodsBO.setAvailableStockNum(item.getGoodsStockNum().intValue());
                }
                // 没有端应用id直接报错
                if (wxChannelInfoBO != null) {
                    sidebarGoodsBO.setAppId(wxChannelInfoBO.getOriginId());
                } else {
                    sidebarGoodsBO.setH5Url(null);
                    sidebarGoodsBO.setMiniUrl(null);
                }
                sidebarGoodsBOList.add(sidebarGoodsBO);
            }
        }

        return new PageResponse<>(sidebarGoodsBOList, sidebarGoodsDTO.getPageNum(), sidebarGoodsDTO.getPageSize(), unpack.getTotalCount());
    }

    /**
     * 查询分销商品列表
     *
     * @author jun.liu05
     * @since 1.0
     */
    public PageResponse<SidebarDistributionGoodsBO> getDistributionGoodsList(SidebarDistributionGoodsDTO dto) {
        if (Objects.isNull(dto) || Objects.isNull(dto.getCurrentVid())
                || Objects.isNull(dto.getPageNum()) || Objects.isNull(dto.getPageSize()) || Objects.isNull(dto.getWeikeWid())) {
            throw new BizException(BaseErrorCode.PARA_ERROR);
        }
        QueryRewardGoodsListRequest goodsRequest = new QueryRewardGoodsListRequest();
        BasicInfoVO basicInfoVO = SidebarConvertor.convertBasicInfo(dto);
        basicInfoVO.setVid(dto.getCurrentVid());
        basicInfoVO.setVidType(dto.getCurrentVidType());

        goodsRequest.setRequestSource(2);
        goodsRequest.setWeikeWid(dto.getWeikeWid());
        goodsRequest.setPageNum(dto.getPageNum());
        goodsRequest.setPageSize(dto.getPageSize());
        goodsRequest.setBasicInfo(basicInfoVO);
        goodsRequest.setGoodsName(dto.getGoodsName());
        goodsRequest.setStatus(dto.getStatus());

        PageInfoResponse<QueryRewardGoodsListResponse> goodsResponse= new PageInfoResponse<>();
        QueryGoodsUrlListResponse urlResponse= new QueryGoodsUrlListResponse();
        WxChannelInfoBO wxChannelInfoBO = null;
        try {
            log.info("查询分销商品入参:{}", JSON.toJSONString(goodsRequest));
            goodsResponse = SoaUtil.unpack(distributionAdapterService.queryRewardGoodsList(goodsRequest));
            if (Objects.isNull(goodsResponse) || CollectionUtils.isEmpty(goodsResponse.getDataList())) {
                return new PageResponse<>();
            }
            List<Long> goodIds = CollUtils.map(goodsResponse.getDataList(), QueryRewardGoodsListResponse::getGoodsId);
            QueryGoodsUrlListRequest queryGoodsUrlListRequest = new QueryGoodsUrlListRequest();
            queryGoodsUrlListRequest.setBasicInfo(basicInfoVO);
            queryGoodsUrlListRequest.setGoodsIdList(goodIds);
            // 获取appid
            wxChannelInfoBO = this.getWxChannelInfo(basicInfoVO.getBosId(), basicInfoVO.getProductInstanceId());

            urlResponse = SoaUtil.unpack(mallAdapterService.queryGoodsUrlList(queryGoodsUrlListRequest));
        } catch (Exception e) {
            log.error("查询分销商品异常,商品返回值:{},url返回值:{}", JSON.toJSONString(goodsResponse), JSON.toJSONString(urlResponse), e);
            return new PageResponse<>();
        }
        List<SidebarDistributionGoodsBO> list = SidebarConvertor.convertSidebarDistributionGoodsBO(goodsResponse.getDataList(), urlResponse.getGoodsUrlOutputList(), wxChannelInfoBO);

        PageResponse<SidebarDistributionGoodsBO> sidebarDistributionGoodsBOPageResponse = new PageResponse<>(list, goodsResponse.getPageNum(), goodsResponse.getPageSize(), goodsResponse.getTotalCount());
        return sidebarDistributionGoodsBOPageResponse;
    }

    public PageResponse<SidebarCouponBO> getCoupons(QuerySidebarCouponsDto couponsDto) {
        if (couponsDto.getBasicInfo() == null) {
            throw new BizException("basicInfo can not be null");
        }
        if (couponsDto.getCurrentVid() == null || couponsDto.getCurrentVid() == 0L) {
            throw new BizException(BaseErrorCode.CURRENTVID_IS_EMPTY.getCode(), BaseErrorCode.CURRENTVID_IS_EMPTY.getMsg());
        }

        ProductInstanceDTO productByVid = this.getProductByVid(couponsDto.getBasicInfo().getVid(), crmProductId);
        if (productByVid == null) {
            throw new BizException("无法获取门店信息");
        }
        String tcode = this.getTCodeByBasicInfo(couponsDto.getBasicInfo());
        QueryCouponsAdapterRequest request = new QueryCouponsAdapterRequest();
        request.setBosId(productByVid.getBosId());
        request.setMerchantId(productByVid.getMerchantId());
        request.setProductId(productByVid.getProductId());
        request.setProductInstanceId(productByVid.getProductInstanceId());
        request.setVid(couponsDto.getCurrentVid());
        request.setTcode(tcode);

        request.setStatus(1);
        request.setNeedAppendRefer(true);
        request.setQueryChannel(MerchantIssueChannelEnum.WECHAT_ENTERPRISE.getCode());
        request.setPublishChannels(Lists.newArrayList(9L));
        request.setPageNum(couponsDto.getPageNum());
        request.setPageSize(couponsDto.getPageSize());
        CouponsSPIResponse<CouponListAdapterResponse> unpack = new CouponsSPIResponse<>();

        try {
            log.info("查询优惠券列表接口: bosId:{}", request.getBosId());
            unpack = SoaUtil.unpack(crmAdapterService.getCustomerCouponTemplate(request));
        } catch (Exception e) {
            log.error("获取优惠券列表的接口发生异常，错误内容：", e);
        }

        if (null == unpack || CollectionUtils.isEmpty(unpack.getPageList())) {
            return new PageResponse<>(Lists.newArrayList(), couponsDto.getPageNum(),
                    couponsDto.getPageSize(), 0L);
        }

        // 获取小程序的appid
        WxChannelInfoBO wxChannelInfoBO = this.getWxChannelInfo(productByVid.getBosId(), productByVid.getProductInstanceId());

        List<SidebarCouponBO> sidebarCouponBoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(unpack.getPageList())) {
            for (CouponListAdapterResponse couponListAdapterResponse : unpack.getPageList()) {
                SidebarCouponBO sidebarCouponBo = new SidebarCouponBO();
                sidebarCouponBo.setCouponTitle(couponListAdapterResponse.getName());
                sidebarCouponBo.setType(couponListAdapterResponse.getCouponType());
                sidebarCouponBo.setCashTicketAmt(couponListAdapterResponse.getCashTicketAmt());
                sidebarCouponBo.setMaxCashTicketAmt(couponListAdapterResponse.getMaxCashTicketAmt());
                sidebarCouponBo.setDiscount(couponListAdapterResponse.getDiscount());
                sidebarCouponBo.setCanCashTicket(couponListAdapterResponse.getCanCashTicket());
                sidebarCouponBo.setReducePriceType(couponListAdapterResponse.getReducePriceType());
                sidebarCouponBo.setCashTicketCondition(couponListAdapterResponse.getCashTicketCondition());
                sidebarCouponBo.setUserTakeLimit(couponListAdapterResponse.getUserTakeLimit());
                sidebarCouponBo.setStock(couponListAdapterResponse.getStock());
//                sidebarCouponBo.setExpDate(couponListAdapterResponse.getExpDate());
                sidebarCouponBo.setCouponTemplateId(couponListAdapterResponse.getCouponTemplateId());
                sidebarCouponBo.setFreightReduceType(couponListAdapterResponse.getFreightReduceType());

                if (couponListAdapterResponse.getCreateTime() != null) {
                    sidebarCouponBo.setCreateTime(DateFormatUtils.format(couponListAdapterResponse.getCreateTime(), "yyyy/MM/dd"));
                }
                if (couponListAdapterResponse.getShare() != null && couponListAdapterResponse.getShare().getShareUrl() != null) {
                    sidebarCouponBo.setH5Url(couponListAdapterResponse.getShare().getShareUrl().getH5Url());
                    sidebarCouponBo.setMiniUrl(couponListAdapterResponse.getShare().getShareUrl().getMiniUrl());
                }
                if (wxChannelInfoBO != null) {
                    sidebarCouponBo.setAppId(wxChannelInfoBO.getOriginId());
                }
                sidebarCouponBoList.add(sidebarCouponBo);
            }
        }

        return new PageResponse<>(sidebarCouponBoList, couponsDto.getPageNum(), couponsDto.getPageSize(), unpack.getTotalCount());
    }

    // 取绑定的小程序或公众号
    private WxChannelInfoBO getWxChannelInfo(Long bosId, Long productInstanceId) {
        WxChannelInfoFindDTO wxChannelInfoFindDTO = new WxChannelInfoFindDTO();
        wxChannelInfoFindDTO.setBosId(bosId);
        wxChannelInfoFindDTO.setProductInstanceId(productInstanceId);
        List<WxChannelInfoBO> wxChannelInfoBOList = SoaUtil.unpack(channelAdapterService.getWxChannelInfo(wxChannelInfoFindDTO));
        if (CollectionUtils.isNotEmpty(wxChannelInfoBOList)) {
            WxChannelInfoBO miniChannel = wxChannelInfoBOList.stream().filter(item -> WxChannelTypeEnum.WECHAT_MINIPROG.getValue().equals(item.getChannelType())
                    && ChannelSubType.WECHAT_MINIPROG_Business.getCode().equals(item.getChannelSubType())).findFirst().orElse(null);
            if (miniChannel == null) {
                return wxChannelInfoBOList.stream().filter(item -> WxChannelTypeEnum.PUBLIC.getValue().equals(item.getChannelType())).findFirst().orElse(null);
            } else {
                return miniChannel;
            }
        }
        return null;
    }

    /**
     * 检查pmc接口的必要参数
     *
     * @param createUrlDTO
     * @Author LeoLee
     * @Date 14:36 2022/7/4
     */
    private void urlRenderParamCheck(CreateUrlDTO createUrlDTO) {
        if (createUrlDTO == null) {
            throw new BizException(BizErrorCodeEnum.NULL_PARAMS.getErrorCode(), BizErrorCodeEnum.NULL_PARAMS.getDesc());
        }
        if (StringUtils.isEmpty(createUrlDTO.getUrl())) {
            throw new BizException(BizErrorCodeEnum.NULL_URL.getErrorCode(), BizErrorCodeEnum.NULL_URL.getDesc());
        }
    }

    /**
     * 只获取pmc参数
     *
     * @param createUrlDTO
     * @return com.weimob.mcloud.wechatwork.customer.service.user.module.bo.sidebar.PmcParamsUrlBO
     * @Author LeoLee
     * @Date 14:37 2022/7/4
     */
    public PmcParamsUrlBO getPmcParamUrl(CreateUrlDTO createUrlDTO) {

        PmcResponse pmcParamValues = getBasePmcParamUrl(createUrlDTO);
        PmcParamsUrlBO pmcParamsUrlBO = new PmcParamsUrlBO();
        // 判断是否渲染短链
        if (createUrlDTO.getNeedShortUrl() != null && createUrlDTO.getNeedShortUrl()) {
            pmcParamsUrlBO.setUrl(getShortUrl(pmcParamValues.getUrl(), createUrlDTO.getUrlConverTypeEnum(), createUrlDTO.getBasicInfo()));
        } else {
            pmcParamsUrlBO.setUrl(pmcParamValues.getUrl());
        }
        return pmcParamsUrlBO;
    }

    /**
     * 获取短链
     *
     * @param url
     * @param urlConverTypeEnum
     * @return java.lang.String
     * @Author LeoLee
     * @Date 14:37 2022/7/4
     */
    private String getShortUrl(String url, UrlConverTypeEnum urlConverTypeEnum, com.weimob.saas.mcloud.wechatwork.integration.common.request.BasicInfo basicInfo) {
        // 必要参数判断
        if (StringUtils.isEmpty(url)) {
            throw new BizException(BizErrorCodeEnum.NULL_URL.getErrorCode(), BizErrorCodeEnum.NULL_URL.getDesc());
        }
        if (urlConverTypeEnum == null) {
            throw new BizException(BizErrorCodeEnum.NULL_SHORT_URL_CONVER_TYPE.getErrorCode(), BizErrorCodeEnum.NULL_SHORT_URL_CONVER_TYPE.getDesc());
        }

        String shortUrlPrefix = null;
        //获取私域，然后获取tcode，通过tcode获取短链的url前缀
        PrivateSphere privateSphereRequest = privateSphereServiceProxy.getPrivateSphereRequest(basicInfo);
        if (privateSphereRequest.getTcode() != null) {
            //前置域名根据tcode转换
            if (TcodeEnum.RU_JIU.getCode().equals(privateSphereRequest.getTcode())) {
                shortUrlPrefix = domainNameCfgDTO.getRujiu();
            } else {
                shortUrlPrefix = domainNameCfgDTO.getWeimob();
            }
        }
        return urlConverProxy.createShortUrl(urlConverTypeEnum, url, shortUrlPrefix).getShortUrl();
    }

    private Guider getGuiderInfo(PrivateSphere privateSphere, String userId, String orgUserId) {

        Employee employee = employeeProxy.fetchEmployeeById(privateSphere, userId, orgUserId, true);

        // 查到导购才拼接 设置导购Id
        if (employee!=null && CollectionUtils.isNotEmpty(employee.getGuiderList())) {
            return employee.getGuiderList().get(0);
        }
        return null;
    }

    /**
     * 填充员工身份信息，
     * 优先级：导购 > 微客
     *
     * @author jun.liu05
     * @since 1.0
     */
    private void getEmployeeIdentityAndFill(CreateUrlDTO createUrlDTO, PrivateSphere privateSphere, String userId, String orgUserId) {

        Employee employee = employeeProxy.fetchEmployeeById(privateSphere, userId, orgUserId, true);

        if (Objects.isNull(employee)) {
            return;
        }

        // 查到导购才拼接 设置导购Id
        if (CollectionUtils.isNotEmpty(employee.getGuiderList())) {
            Guider guider = employee.getGuiderList().get(0);
            createUrlDTO.getCreateShortCodeDTO().setGuideWid(guider.getWid());
            createUrlDTO.getCreateShortCodeDTO().setGuideVid(guider.getStoreId());
            // 有导购直接返回
            return;
        }

        // 看下是否有微客身份，有则设置微客身份
        Map<Integer, String> identityMap = CollUtils.toMap(employee.getEmployeeIdentityList(), EmployeeIdentity::getIdentityType, EmployeeIdentity::getIdentityId);
        if (identityMap.containsKey(IdentityTypeEnum.DISTRIBUTION_CUSTOMER.getCode())) {
            createUrlDTO.getCreateShortCodeDTO().setWeikeWid(identityMap.get(IdentityTypeEnum.DISTRIBUTION_CUSTOMER.getCode()));
        }
    }

    /**
     * 基础获取pmc的分享参
     *
     * @param createUrlDTO
     * @return com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.pmc.response.PmcResponse
     * @date 14:38 2022/7/4
     */
    private PmcResponse getBasePmcParamUrl(CreateUrlDTO createUrlDTO) {
        //必要参数检查
        urlRenderParamCheck(createUrlDTO);
        CreateShortCodeDTO createShortCodeDTO = createUrlDTO.getCreateShortCodeDTO();
        //检查是否有企微userid
        boolean isRequiredParamsExist = createShortCodeDTO != null
                && (StringUtils.isNotEmpty(createShortCodeDTO.getUserId()) || StringUtils.isNotEmpty(createShortCodeDTO.getOrgUserId()));
        if (!isRequiredParamsExist) {
            return new PmcResponse(null, createUrlDTO.getUrl(), null);
        }
        //根据企微userId获取员工信息
        List<EmployeeBO> employeeBOList = getEmployeeInfoAndFillId(createUrlDTO);
        //判断是否存在员工手机号
        //NOSONAR
        if (CollectionUtils.isEmpty(employeeBOList) || Objects.isNull(employeeBOList.get(0))) {
            return new PmcResponse(null, createUrlDTO.getUrl(), null);
        }
        // 获取pmc加参的wid和vid，这个有个优先级注意
        PmcRequest pmcRequest = new PmcRequest();
        getPmcWidAndVid(employeeBOList.get(0), createUrlDTO, pmcRequest);

        if (pmcRequest.getWid() == null || pmcRequest.getVid() == null) {
            return new PmcResponse(null, createUrlDTO.getUrl(), null);
        }
        //请求pmc加参渲染url
        log.info("生成pmc短参入参：createUrlDTO:{},wid:{},vid:{}", JSON.toJSONString(createUrlDTO), pmcRequest.getWid(), pmcRequest.getVid());
        return pmcProxy.getPmcParamValues(createUrlDTO.getBasicInfo(), PmcOperationSourceEnum.MERCHANT, pmcRequest.getWid(), createUrlDTO.getUrl(), pmcRequest.getVid());
    }

    /**
     * 这里是为了解决分享链接自带vid参数被覆盖导致的进店逻辑错误问题
     * 不能直接使用basicinfo的vid，因为url中的vid可能不是当前店铺的
     * 目前获取当前分享人所属店铺的vid，当前分享人就是createUrlDTO中的userId或者orgUserId对应的那个人
     *
     * @param createUrlDTO
     * @return java.lang.Long
     * @Date 14:28 2022/7/11
     */
    private Long getPmcVid(CreateUrlDTO createUrlDTO) {
        if (createUrlDTO == null) {
            return null;
        }
        if (createUrlDTO.getCreateShortCodeDTO().getGuideVid() != null) {
            return createUrlDTO.getCreateShortCodeDTO().getGuideVid();
        }
        return null;
    }

    /**
     * 这里获取pmc加参的vid和wid
     * 优先级: 导购BWid > 微客CWid
     *
     * vid逻辑：
     * 导购:用的是目前获取当前分享人所属店铺的vid，当前分享人就是createUrlDTO中的userId或者orgUserId对应的那个人，
     * 不能用basicinfo的vid，否则会导致进店逻辑错误
     *
     * 微客:用的就是当前分享链接请求当前的vid
     *
     * @author jun.liu05
     * @since 1.0
     */
    private void getPmcWidAndVid(EmployeeBO employeeBO, CreateUrlDTO createUrlDTO, PmcRequest pmcRequest) {
        if (Objects.isNull(employeeBO) || Objects.isNull(createUrlDTO) || Objects.isNull(pmcRequest)) {
            return;
        }

        if (StringUtils.isNotBlank(employeeBO.getMobile())) {
            //获取员工手机号并请求Passport获取wid 这里保持原来的逻辑
            List<PhoneAndZoneAndWidResponse> phoneAndZoneAndWidResponseList = passPortAccountFetchProxy.batchGetWidByPhoneAndZone(Arrays.asList(employeeBO.getMobile()));
            if (CollectionUtils.isNotEmpty(phoneAndZoneAndWidResponseList)) {
                pmcRequest.setWid(phoneAndZoneAndWidResponseList.get(0).getWid());
                // 取导购的门店vid
                if (createUrlDTO.getCreateShortCodeDTO().getGuideVid() != null) {
                    pmcRequest.setVid(createUrlDTO.getCreateShortCodeDTO().getGuideVid());
                    // 必须满足wid有值，并且vid也有值，代表有导购的就直接返回了，老逻辑 （这里不返回下面wid会覆盖的）
                    return;
                }
            }
        }


        Map<Integer, String> map = CollUtils.toMap(employeeBO.getEmployeeIdentityBOList(),
                com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.bo.EmployeeIdentityBO::getIdentityType,
                com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.bo.EmployeeIdentityBO::getIdentityId);
        if (map.containsKey(IdentityTypeEnum.DISTRIBUTION_CUSTOMER.getCode())
                && StringUtils.isNotBlank(map.get(IdentityTypeEnum.DISTRIBUTION_CUSTOMER.getCode()))) {
            pmcRequest.setWid(Long.valueOf(map.get(IdentityTypeEnum.DISTRIBUTION_CUSTOMER.getCode())));
            // 取当前vid
            if (createUrlDTO.getBasicInfo() != null && createUrlDTO.getBasicInfo().getVid() != null) {
                pmcRequest.setVid(createUrlDTO.getBasicInfo().getVid());
            }
        }
    }
    /**
     * 根据短参||pmc参数获取员工信息，并且补充userId或者orgUserid
     *
     * @param createUrlDTO
     * @Date 16:27 2022/7/4
     */
    private List<EmployeeBO> getEmployeeInfoAndFillId(CreateUrlDTO createUrlDTO) {
        CreateShortCodeDTO createShortCodeDTO = createUrlDTO.getCreateShortCodeDTO();
        //构造请求参数
        EmployeeDTO employeeReq = new EmployeeDTO();
        employeeReq.setCurrentVid(createUrlDTO.getCurrentVid());
        employeeReq.setExceptDeleted(Boolean.FALSE);
        employeeReq.setProductInstanceId(createUrlDTO.getBasicInfo().getProductInstanceId());
        employeeReq.setBosId(createUrlDTO.getBasicInfo().getBosId());
        employeeReq.setVid(createUrlDTO.getBasicInfo().getVid());
        List<EmployeeBO> employeeBOList = new ArrayList<>();
        //根据userId或者orgUserId请求员工信息
        if (StringUtils.isNotEmpty(createShortCodeDTO.getUserId())) {
            employeeReq.setUserIds(Arrays.asList(createShortCodeDTO.getUserId()));
            employeeBOList = SoaResponseUtil.unpack(orgDepartmentUserExport.getUsersByUserIds(employeeReq));
        } else if (StringUtils.isEmpty(createShortCodeDTO.getUserId()) && StringUtils.isNotEmpty(createShortCodeDTO.getOrgUserId())) {
            employeeReq.setEmployeeId(createShortCodeDTO.getOrgUserId());
            employeeBOList = SoaResponseUtil.unpack(orgDepartmentUserExport.getUsersByIds(employeeReq));
        }
        //补充id
        if (CollectionUtils.isNotEmpty(employeeBOList)) {
            EmployeeBO employeeBO = employeeBOList.get(0); // NOSONAR
            if (Objects.isNull(employeeBO)) {
                return employeeBOList;
            }
            createShortCodeDTO.setUserId(employeeBO.getUserId());
            createShortCodeDTO.setOrgUserId(employeeBO.getOrgUserId());
        }
        return employeeBOList;
    }

    /**
     * 同时渲染pmc和短参
     *
     * @param createUrlDTO
     * @return com.weimob.mcloud.wechatwork.customer.service.user.module.bo.sidebar.ShortCodePmcUrlBO
     * @date 14:39 2022/7/4
     */
    public ShortCodePmcUrlBO getPmcShortCodeUrl(CreateUrlDTO createUrlDTO) {
        String url = createUrlDTO.getUrl();
        log.info("getPmcShortCodeUrlInvokeInfo|userId:{}|orgUserId:{}|url={}", createUrlDTO.getCreateShortCodeDTO().getUserId(), createUrlDTO.getCreateShortCodeDTO().getOrgUserId(), url);


        //如果开头出现#直接返回，不进行下面的加参逻辑
        if (StringUtils.startsWith(url, "#")) {
            ShortCodePmcUrlBO shortCodePmcUrlBO = new ShortCodePmcUrlBO();
            shortCodePmcUrlBO.setUrl(url);
            return shortCodePmcUrlBO;
        }

        /*
        把url中的末尾#串截掉
        baidu.com/s?id=1#re#rd 会保存为baidu.com/s?id=1
         */
        String urlPrefix = StringUtils.substringBefore(url, "#");
        /*
        截取第一个#后的串
        baidu.com/s?id=1#re#rd 会保存为re#rd
         */
        String urlSuffix = StringUtils.substringAfter(url, "#");
        createUrlDTO.setUrl(urlPrefix);
        //获取短参
        CreateShortCodeResponse createShortCodeResponse = getCreateShortCode(createUrlDTO);
        //渲染pmc参数,放在短参后面请求是为了获取短参中导购的wid和vid
        PmcResponse pmcParamValues = getBasePmcParamUrl(createUrlDTO);
        //拼接pmc和短参
        String shortUrlParam = replaceOrAdd(pmcParamValues.getUrl(), SidebarConstant.QWZS_TICKET, createShortCodeResponse.getShortCode());

        //获取当前传给pmc的vid，这个vid就是当前userId或者orgUserId对应的员工的所在店铺的vid
        shortUrlParam = addJsonShortCode(shortUrlParam, createShortCodeResponse.getShortCode());

        //拼接上#后缀
        if (StringUtils.isNotBlank(urlSuffix)) {
            shortUrlParam = shortUrlParam + "#" + urlSuffix;
        }

        ShortCodePmcUrlBO shortCodePmcUrlBO = new ShortCodePmcUrlBO();

        shortCodePmcUrlBO.setUrl(shortUrlParam);
        // 判断是否渲染短链
        if (createUrlDTO.getNeedShortUrl() != null && createUrlDTO.getNeedShortUrl()) {
            shortCodePmcUrlBO.setUrl(getShortUrl(shortCodePmcUrlBO.getUrl(), createUrlDTO.getUrlConverTypeEnum(), createUrlDTO.getBasicInfo()));
        }
        return shortCodePmcUrlBO;
    }


    /**
     * 对target进行对应kv值增加，或者v值替换
     * 如果key值存在，替换value值，如果key值不存在，增加kv对
     *
     * @param target 目标
     * @param key    key值
     * @param value  value值
     * @return 处理过的target字符串，不新建对象
     */
    private static String replaceOrAdd(String target, String key, String value) {
        // 1.非空校验 & 初始化字符串
        if (StringUtils.isBlank(target)) {
            return target;
        }
        try {
            UrlQueryUtil urlQueryUtil = UrlQueryUtil.of(target);
            Map<CharSequence, CharSequence> queryMap = urlQueryUtil.getQueryMap();
            queryMap.put(key, value);
            int idx = target.indexOf("?");
            String prefix = (idx != -1 ? target.substring(0, idx) : target) + "?";
            String finalUrl = prefix + urlQueryUtil.build();
            log.info("shortCode before replaceOrAdd:{}, after replaceOrAdd:{}", target, finalUrl);
            return finalUrl;
        } catch (Exception e) {
            log.error("get shortCode replaceOrAdd failed, target:{}, key:{}, value:{}, cause:{}", target, key, value, e.getMessage(), e);
        }
        return target;
    }

    /**
     * 以json的形式再给url拼接json形式的短参
     *
     * @param url       已经拼接短参的url
     * @param shortCode 短参
     * @return
     */
    private static String addJsonShortCode(String url, String shortCode) {
        if (StringUtils.isEmpty(url) || StringUtils.isEmpty(shortCode)) {
            return url;
        }
        //构造营销活动需要的json形式的value
        Map<String, String> shortCodeJson = new HashMap<>();
        shortCodeJson.put(SidebarConstant.QWZS_TICKET, shortCode);
        String jsonShortCode = JSON.toJSONString(shortCodeJson);
        String encode = "";
        try {
            encode = URLEncoder.encode(jsonShortCode, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new BizException("url转义失败");
        }
        StringBuffer sb = new StringBuffer(url);
        sb.append("&extra_args=");
        sb.append(encode);

        return sb.toString();
    }


    /**
     * 获取短参链接优化版本，补充userId或者orgUserId
     *
     * @param createUrlDTO
     * @return com.weimob.mcloud.wechatwork.customer.service.user.module.bo.sidebar.ShortCodeBO
     * @Author LeoLee
     * @Date 16:47 2022/7/4
     */
    public ShortCodeBO getShortCodeV2(CreateUrlDTO createUrlDTO) {
        //如果url是#开头则不进行之后的加参逻辑直接返回
        if (StringUtils.startsWith(createUrlDTO.getUrl(), "#")) {
            ShortCodeBO shortCodeBO = new ShortCodeBO();
            shortCodeBO.setUrl(createUrlDTO.getUrl());
            return shortCodeBO;
        }

        //获取短参
        CreateShortCodeResponse createShortCodeResponse = getCreateShortCode(createUrlDTO);
        StringBuilder url = new StringBuilder();
        // 导购需要获取导购埋点数据
        if (createUrlDTO.getCreateShortCodeDTO().getGuideWid() != null && createUrlDTO.getCreateShortCodeDTO().getGuideWid() != 0L
                && createUrlDTO.getCreateShortCodeDTO().getGuideVid() != null && createUrlDTO.getCreateShortCodeDTO().getGuideVid() != 0L) {

            PmcAdapterResponse pmcAdapterResponse = new PmcAdapterResponse();
            ProductInstanceDTO productByVid = this.getProductByVid(createUrlDTO.getCreateShortCodeDTO().getGuideVid(), guideProductId);
            if (productByVid != null) {
                PmcParameterRequest.BasicInfoBean paramBasicInfo = new PmcParameterRequest.BasicInfoBean();
                paramBasicInfo.setBosId(productByVid.getBosId());
                paramBasicInfo.setMerchantId(productByVid.getMerchantId());
                paramBasicInfo.setVid(createUrlDTO.getCurrentVid());
                paramBasicInfo.setProductId(productByVid.getProductId());
                paramBasicInfo.setProductInstanceId(productByVid.getProductInstanceId());
                paramBasicInfo.setCid(productByVid.getProductInstanceId());

                PmcParameterRequest pmcParameterRequest = new PmcParameterRequest();
                pmcParameterRequest.setUrl(createUrlDTO.getUrl());
                pmcParameterRequest.setWid(createUrlDTO.getCreateShortCodeDTO().getGuideWid());
                Map<String, Object> map = new HashMap<>();
                map.put("wid", createUrlDTO.getCreateShortCodeDTO().getGuideWid());
                pmcParameterRequest.setExtMap(map);
                pmcParameterRequest.setBasicInfo(JSON.parseObject(JSON.toJSONString(paramBasicInfo), PmcParameterRequest.BasicInfoBean.class));

                try {
                    log.info("生成导购短参接口: request:{}", JSON.toJSONString(pmcParameterRequest));
                    pmcAdapterResponse = SoaUtil.unpack(cmsAdapterService.getPmcParam(pmcParameterRequest));
                } catch (Exception e) {
                    log.error("获取导购带参的接口发生异常，错误内容：", e);
                }
            }

            if (StringUtils.isNotEmpty(pmcAdapterResponse.getUrl())) {
                url.append(pmcAdapterResponse.getUrl());
            } else {
                url.append(createUrlDTO.getUrl());
            }
        } else {
            url.append(createUrlDTO.getUrl());
        }
        // 拼接短参
        ShortCodeBO shortCodeBO = new ShortCodeBO();
        String shortUrlParam = replaceOrAdd(url.toString(), SidebarConstant.QWZS_TICKET, createShortCodeResponse.getShortCode());
        //以json的形式再给url拼接json形式的短参
        shortCodeBO.setUrl(addJsonShortCode(shortUrlParam, createShortCodeResponse.getShortCode()));
        // 判断是否渲染短链
        if (createUrlDTO.getNeedShortUrl() != null && createUrlDTO.getNeedShortUrl()) {
            shortCodeBO.setUrl(getShortUrl(shortCodeBO.getUrl(), createUrlDTO.getUrlConverTypeEnum(), createUrlDTO.getBasicInfo()));
        }
        return shortCodeBO;
    }

    /**
     * 获取短参
     *
     * @param createUrlDTO
     * @return com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.shortcode.response.CreateShortCodeResponse
     * @Author LeoLee
     * @Date 16:40 2022/7/4
     */
    private CreateShortCodeResponse getCreateShortCode(CreateUrlDTO createUrlDTO) {
        //补充userId或者orgUserId
        this.getEmployeeInfoAndFillId(createUrlDTO);
        //填充活动种类参数campaignCategory
        this.fillCampaignCategory(createUrlDTO.getCreateShortCodeDTO());
        //查询员工身份相关信息：导购wid和vid > 微客wid
        if (StringUtils.isNotEmpty(createUrlDTO.getCreateShortCodeDTO().getUserId()) || StringUtils.isNotEmpty(createUrlDTO.getCreateShortCodeDTO().getOrgUserId())) {
            //JNBY多bos兼容，通过bosId和corpId确定唯一私域
            PrivateSphere privateSphere = privateSphereThird.fetchByBosIdCorpId(createUrlDTO.getBasicInfo());

            /*Guider guiderInfo = getGuiderInfo(privateSphere, createUrlDTO.getCreateShortCodeDTO().getUserId(), createUrlDTO.getCreateShortCodeDTO().getOrgUserId());
            if (guiderInfo != null) {
                createUrlDTO.getCreateShortCodeDTO().setGuideWid(guiderInfo.getWid());
                createUrlDTO.getCreateShortCodeDTO().setGuideVid(guiderInfo.getStoreId());
            }*/
            getEmployeeIdentityAndFill(createUrlDTO, privateSphere, createUrlDTO.getCreateShortCodeDTO().getUserId(), createUrlDTO.getCreateShortCodeDTO().getOrgUserId());
        }
        // 生成企微助手短参
        StringBuilder content = new StringBuilder();
        Map<String, Object> fieldMap = JSONObject.parseObject(JSONObject.toJSONString(createUrlDTO.getCreateShortCodeDTO()), Map.class);
        for (String key : fieldMap.keySet()) {
            if (Objects.nonNull(fieldMap.get(key)) && StringUtils.isNotBlank(String.valueOf(fieldMap.get(key)))) {
                content.append(key).append("=").append(fieldMap.get(key).toString()).append("&");
            }
        }
        content.deleteCharAt(content.length() - 1);
        CreateShortCodeRequest createShortCodeRequest = new CreateShortCodeRequest();
        createShortCodeRequest.setScene(BaseConstant.SCENCE);
        createShortCodeRequest.setContent(content.toString());

        log.info("生成短参接口: request:{}", JSON.toJSONString(createShortCodeRequest));
        CreateShortCodeResponse createShortCodeResponse = SoaResponseUtil.unpack(shortCodeAdapterService.createShortParam(createShortCodeRequest));
        return createShortCodeResponse;
    }

    /**
     * 解析短参
     *
     * @param shortCode
     * @param scene
     * @return com.weimob.mcloud.wechatwork.customer.service.user.module.bo.sidebar.ShortCodeParamsInfoBO
     * @Author LeoLee
     */
    public ShortCodeParamsInfoBO getShortCodeInfo(String shortCode, String scene) {
        if (StringUtils.isEmpty(shortCode) || StringUtils.isEmpty(scene)) {
            throw new BizException("parse shortCode failed, cause missing necessary params");
        }
        //请求解析短参
        SoaResponse<GetShortCodeResponse, UrlErrorVo> response = shortParamService.getShortCode(shortCode, scene);
        GetShortCodeResponse shortCodeInfo = SoaUtil.unpack(response);
        //解析短参的内容，String to Map
        return buildShortCodeInfoResult(shortCodeInfo);
    }

    private ShortCodeParamsInfoBO buildShortCodeInfoResult(GetShortCodeResponse shortCodeResponse) {
        ShortCodeParamsInfoBO shortCodeParamsInfoBO = new ShortCodeParamsInfoBO();
        shortCodeParamsInfoBO.setShortCode(shortCodeResponse.getShortCode());
        shortCodeParamsInfoBO.setContent(shortCodeResponse.getContent());
        shortCodeParamsInfoBO.setParams(parseShortCodeContent(shortCodeResponse.getContent()));
        shortCodeParamsInfoBO.setScene(shortCodeResponse.getScene());
        return shortCodeParamsInfoBO;
    }

    /**
     * 短参内容转map
     *
     * @param content
     * @return
     * @Author LeoLee
     */
    private Map<String, String> parseShortCodeContent(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        //获取每一个参数
        String[] paramKV = content.split("&");
        if (paramKV == null || paramKV.length < 1) {
            return null;
        }
        //参数转map
        Map<String, String> resultMap = new HashMap<>();
        for (int i = 0; i < paramKV.length; i++) {
            String[] param = paramKV[i].split("=");
            if (param != null && param.length == 2) {
                resultMap.put(param[0], param[1]);
            }
        }
        return resultMap;
    }

    /**
     * 填充活动种类
     *
     * @param createShortCodeDTO
     */
    private void fillCampaignCategory(CreateShortCodeDTO createShortCodeDTO) {
        if (Objects.isNull(createShortCodeDTO) || StringUtils.isBlank(createShortCodeDTO.getCampaignRefer()) || Objects.isNull(createShortCodeDTO.getCampaignProductId())) {
            return;
        }
        CampaignCategoryConfigBO campaignCategoryConfigBO = campaignApolloConfig.getCampaignCategoryMapping(createShortCodeDTO.getCampaignProductId(), createShortCodeDTO.getCampaignRefer());
        log.info("fillCampaignCategory campaignCategoryConfigBO: {}", campaignCategoryConfigBO);
        createShortCodeDTO.setCampaignCategory(Objects.nonNull(campaignCategoryConfigBO) ? campaignCategoryConfigBO.getCampaignCategory() : null);
    }


    public ShortCodeBO getShortCode(CreateUrlDTO createUrlDTO) {
        // 生成企微助手短参
        StringBuilder content = new StringBuilder();
        Map<String, Object> fieldMap = JSON.parseObject(JSONObject.toJSONString(createUrlDTO.getCreateShortCodeDTO()), Map.class);
        for (String key : fieldMap.keySet()) {
            if (fieldMap.get(key) != null && StringUtils.isNotEmpty(String.valueOf(fieldMap.get(key)))) {
                content.append(key).append("=").append(fieldMap.get(key).toString()).append("&");
            }
        }
        content.deleteCharAt(content.length() - 1);

        CreateShortCodeRequest createShortCodeRequest = new CreateShortCodeRequest();
        createShortCodeRequest.setScene(BaseConstant.SCENCE);
        createShortCodeRequest.setContent(content.toString());

        log.info("生成短参接口: request:{}", JSON.toJSONString(createShortCodeRequest));
        CreateShortCodeResponse createShortCodeResponse = SoaResponseUtil.unpack(shortCodeAdapterService.createShortParam(createShortCodeRequest));

        StringBuilder url = new StringBuilder();
        // 导购需要获取导购埋点数据
        if (createUrlDTO.getCreateShortCodeDTO().getGuideWid() != null && createUrlDTO.getCreateShortCodeDTO().getGuideWid() != 0L
                && createUrlDTO.getCreateShortCodeDTO().getGuideVid() != null && createUrlDTO.getCreateShortCodeDTO().getGuideVid() != 0L) {

            ProductInstanceDTO productByVid = this.getProductByVid(createUrlDTO.getCreateShortCodeDTO().getGuideVid(), guideProductId);
            PmcAdapterResponse pmcAdapterResponse = new PmcAdapterResponse();
            if (productByVid != null) {
                PmcParameterRequest.BasicInfoBean paramBasicInfo = new PmcParameterRequest.BasicInfoBean();
                paramBasicInfo.setBosId(productByVid.getBosId());
                paramBasicInfo.setMerchantId(productByVid.getMerchantId());
                paramBasicInfo.setVid(createUrlDTO.getCurrentVid());
                paramBasicInfo.setProductId(productByVid.getProductId());
                paramBasicInfo.setProductInstanceId(productByVid.getProductInstanceId());
                paramBasicInfo.setCid(productByVid.getProductInstanceId());

                PmcParameterRequest pmcParameterRequest = new PmcParameterRequest();
                pmcParameterRequest.setUrl(createUrlDTO.getUrl());
                pmcParameterRequest.setWid(createUrlDTO.getCreateShortCodeDTO().getGuideWid());
                Map<String, Object> map = new HashMap<>();
                map.put("wid", createUrlDTO.getCreateShortCodeDTO().getGuideWid());
                pmcParameterRequest.setExtMap(map);
                pmcParameterRequest.setBasicInfo(JSON.parseObject(JSON.toJSONString(paramBasicInfo), PmcParameterRequest.BasicInfoBean.class));

                try {
                    log.info("生成导购短参接口: request:{}", JSON.toJSONString(pmcParameterRequest));
                    pmcAdapterResponse = SoaUtil.unpack(cmsAdapterService.getPmcParam(pmcParameterRequest));
                } catch (Exception e) {
                    log.error("获取导购带参的接口发生异常，错误内容：", e);
                }
            }

            if (StringUtils.isNotEmpty(pmcAdapterResponse.getUrl())) {
                url.append(pmcAdapterResponse.getUrl());
            } else {
                url.append(createUrlDTO.getUrl());
            }
        } else {
            url.append(createUrlDTO.getUrl());
        }
        ShortCodeBO shortCodeBO = new ShortCodeBO();
        String shortUrlParam = replaceOrAdd(url.toString(), SidebarConstant.QWZS_TICKET, createShortCodeResponse.getShortCode());
        shortCodeBO.setUrl(shortUrlParam);
        return shortCodeBO;
    }

    public PageResponse<OrderBO> queryOrderList(OrderListDTO orderListDTO) {
        // 没传wid 获取wid
        QueryOrderInBusinessDTO queryParameter = orderListDTO.getQueryParameter();
        OrderQueryParameter orderQueryParameter = JSON.parseObject(JSON.toJSONString(queryParameter), OrderQueryParameter.class);
        if (queryParameter != null && CollectionUtils.isNotEmpty(queryParameter.getOrderStatuses())) {
            orderQueryParameter.setStatuses(queryParameter.getOrderStatuses());
        }
        // 订单查询范围。支持的类型包括：1-订单项信息；2-履约信息；3-售后信息。不传则只展示订单信息
        orderQueryParameter.setOrderDomains(Lists.newArrayList(1, 2));

        // C端传客户wid
        Long wid = null;
        if (orderListDTO.getExternalUserWid() == null || orderListDTO.getExternalUserWid() == 0L) {
            if (orderListDTO.getExternalUserId() != null) {
                PrivateSphere privateSphere = this.getPrivateSphereByBasicInfo(orderListDTO.getBasicInfo());
                wid = customerThird.getSuperWid(privateSphere.getBosId(), orderListDTO.getExternalUserId(), privateSphere.getCorpId());
            }
        } else {
            wid = orderListDTO.getExternalUserWid();
        }
        if (wid == null) {
            throw new BizException(BaseErrorCode.PARMA_EXCPETION.getCode(), BaseErrorCode.PARMA_EXCPETION.getMsg());
        }
        orderQueryParameter.setUserWid(wid);

        if (orderQueryParameter.getQueryTime() != null && (orderQueryParameter.getQueryTime().getStartTime() == null || orderQueryParameter.getQueryTime().getEndTime() == null)) {
            OrderQueryTimeReq orderQueryTimeReq = new OrderQueryTimeReq();
            orderQueryTimeReq.setType(0);
            orderQueryTimeReq.setStartTime(new Date().getTime() - 12 * 30 * 24 * 60 * 60 * 1000);
            orderQueryTimeReq.setEndTime(new Date().getTime());
            orderQueryParameter.setQueryTime(orderQueryTimeReq);
        }

        OrderListAdapterRequest orderListAdapterRequest = new OrderListAdapterRequest();

        // B端查询当前节点的
        if (orderListDTO.getCurrentVid() != null) {
            orderQueryParameter.setProcessVids(Lists.newArrayList(orderListDTO.getCurrentVid()));
        }
        orderListAdapterRequest.setQueryParameter(orderQueryParameter);

        ProductInstanceDTO productByVid = this.getProductByVid(orderListDTO.getCurrentVid() != null ? orderListDTO.getCurrentVid() : orderListDTO.getBasicInfo().getVid(), mallProductId);
        if (productByVid == null) {
            return new PageResponse<>(new ArrayList<>(), orderListDTO.getPageNum(),
                    orderListDTO.getPageSize(), 0L);
        }
        String tcode = this.getTCodeByBasicInfo(orderListDTO.getBasicInfo());
        OrderListAdapterRequest.BasicInfoBean basicInfoBean = new OrderListAdapterRequest.BasicInfoBean();
        basicInfoBean.setBosId(productByVid.getBosId());
        basicInfoBean.setMerchantId(productByVid.getMerchantId());
        basicInfoBean.setProductId(productByVid.getProductId());
        basicInfoBean.setProductInstanceId(productByVid.getProductInstanceId());
        basicInfoBean.setVid(orderListDTO.getBasicInfo().getVid());
        basicInfoBean.setTcode(tcode);
        orderListAdapterRequest.setBasicInfo(basicInfoBean);

        orderListAdapterRequest.setPageNum(orderListDTO.getPageNum());
        orderListAdapterRequest.setPageSize(orderListDTO.getPageSize());

        log.info("获取订单列表接口: bosId:{}", productByVid.getBosId());
        MallPageInfoResponse<OrderIpaasAdapterResponse> unpack = SoaUtil.unpack(mallAdapterService.getIpaasOrderList(orderListAdapterRequest));
        if (null == unpack || CollectionUtils.isEmpty(unpack.getPageList())) {
            return new PageResponse<>(Lists.newArrayList(), orderListDTO.getPageNum(),
                    orderListDTO.getPageSize(), 0L);
        }


        List<OrderBO> orderListBOList = new ArrayList<>();
        for (OrderIpaasAdapterResponse orderIpaasAdapterResponse : unpack.getPageList()) {
            String pageListString = JSON.toJSONString(orderIpaasAdapterResponse);
            if (StringUtils.isNotBlank(pageListString)) {
                try {
                    OrderBO orderBO = JSON.parseObject(pageListString, OrderBO.class);
                    orderListBOList.add(orderBO);
                } catch (Exception exception) {
                    log.error("queryOrderList 订单对象转换异常,e", exception);
                    return new PageResponse<>(Lists.newArrayList(), orderListDTO.getPageNum(),
                            orderListDTO.getPageSize(), 0L);
                }
            }
        }


        return new PageResponse<>(orderListBOList, orderListDTO.getPageNum(),
                orderListDTO.getPageSize(), unpack.getTotalCount());
    }

    public OrderBO queryOrderDetail(OrderDetailDTO orderDetailDTO) {
        // B端查询当前节点的
        if (orderDetailDTO.getCurrentVid() == null) {
            orderDetailDTO.setCurrentVid(orderDetailDTO.getBasicInfo().getVid());
        }
        ProductInstanceDTO productByVid = this.getProductByVid(orderDetailDTO.getCurrentVid(), mallProductId);
        if (productByVid == null) {
            throw new BizException(BaseErrorCode.PARMA_EXCPETION.getCode(), "根据商城产品id和当前节点id, 查询不到产品实例信息");
        }
        String tcode = this.getTCodeByBasicInfo(orderDetailDTO.getBasicInfo());

        OrderDetailAdapterRequest orderListAdapterRequest = new OrderDetailAdapterRequest();
        orderListAdapterRequest.setOrderNo(orderDetailDTO.getOrderNo());
        // 订单查询范围。支持的类型包括：1-订单项信息；2-履约信息；3-售后信息。不传则只展示订单信息
        orderListAdapterRequest.setOrderDomains(Lists.newArrayList(1, 2));
        orderListAdapterRequest.setOperationSource(2L);
        OrderDetailAdapterRequest.BasicInfoBean basicInfoBean = new OrderDetailAdapterRequest.BasicInfoBean();
        basicInfoBean.setBosId(productByVid.getBosId());
        basicInfoBean.setMerchantId(productByVid.getMerchantId());
        basicInfoBean.setProductId(productByVid.getProductId());
        basicInfoBean.setProductInstanceId(productByVid.getProductInstanceId());
        basicInfoBean.setVid(orderDetailDTO.getCurrentVid());
        orderListAdapterRequest.setBasicInfo(basicInfoBean);
        orderListAdapterRequest.setTcode(tcode);

        // 查订单详情
        log.info("获取订单详情接口: OrderNo:{}", orderDetailDTO.getOrderNo());
        OrderIpaasAdapterResponse orderDetail = SoaUtil.unpack(mallAdapterService.getIpaasOrderDetail(orderListAdapterRequest));

        String pageListString = JSON.toJSONString(orderDetail);
        OrderBO orderBO = JSON.parseObject(pageListString, OrderBO.class);
        return orderBO;
    }


    private String getTCodeByBasicInfo(BasicInfo basicInfo) {
        PrivateSphere privateSphere = new PrivateSphere();
        String tCode = null;
        if (basicInfo != null) {
            BeanUtils.copyProperties(basicInfo, privateSphere);

            if (null == privateSphere.getProductId()) {
                privateSphere.setProductId(aewcProductId);
            }

            privateSphere = SoaUtil.unpack(privateSphereService.simpleFetch(privateSphere));
            if (privateSphere != null) {
                tCode = privateSphere.getTcode();
            }
        }

        return tCode;
    }

}
